package com.paomi.client.view;

import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.Path;
import android.graphics.PixelFormat;
import android.graphics.RectF;
import android.graphics.drawable.Drawable;
import android.support.annotation.Nullable;
import android.util.AttributeSet;
import android.view.View;
import android.widget.ImageView;

import com.paomi.client.MyApplication;
import com.paomi.client.R;
import com.paomi.client.utils.Util;

/**
 * Created by pc on 2018/11/16
 * Describe:自定义带气泡的进度条
 * http://www.cnblogs.com/hacjy/p/7390479.html
 * （1）图片，作为文本的背景图，这个背景图应该伸缩不失真，建议用.9图；
 *
 * （2）文本，有颜色和大小，显示在图片上，居中显示；
 *
 * （3）默认进度条，有颜色和宽高；
 *
 * （4）真正的进度条：有颜色和进度值、宽高。它比较特殊的是当进度不等于100%时，左边是圆弧，右边是直线型（没有圆角）。
 * com.paomi.client.view
 */
public class ProgressBubbleView extends View {
    private Context mContext;
    /**
     * 背景图画笔
     */
    private Paint mBackgroundPaint;
    /**
     * 进度画笔
     */
    private Paint mProgressPaint;
    /**
     * 文本画笔
     */
    private Paint mTextPaint;
    /**
     * 图片画笔
     */
    private Paint mPicturePaint;
    /**
     * 背景矩形颜色
     */
    private int mBackgroundColor = Color.BLACK;
    /**
     * 进度矩形颜色
     */
    private int mProgressColor = Color.GRAY;
    /**
     * 文本颜色
     */
    private int mTextColor = Color.BLACK;
    /**
     * 文本大小
     */
    private int mTextSize = 16;
    /**
     * 控件宽高：控件必须在布局中指定宽高大小
     */
    private int mWidth;
    private int mHeight;
    /**
     * 进度矩形高度
     * 14dp
     */
    private int mProgressHeight = Util.dip2px(MyApplication.getAppContext(),14);
    /**
     * 图片宽高
     */
    private int mPicWidth;
    private int mPicHeight;
    /**
     * 矩形4个角的半径坐标,左上，右上，右下，左下（顺时针）
     */
    private float[] mRadiusArr = new float[]{0f,0f,0f,0f,0f,0f,0f,0f};
    /**
     * 进度
     */
    private float mProgress;
    /**
     * 文本
     */
    private String mText;

    private View inflate;

    public ProgressBubbleView(Context context) {
        super(context);
        initView(context);
    }

    public ProgressBubbleView(Context context, @Nullable AttributeSet attrs) {
        super(context, attrs);
        initView(context);
    }

    public ProgressBubbleView(Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        initView(context);
    }

    private void initView(Context context){
        mContext = context;

        mBackgroundPaint = new Paint();
        mBackgroundPaint.setStyle(Paint.Style.FILL);
        mBackgroundPaint.setStrokeWidth(1);

        mBackgroundPaint.setAntiAlias(true);

        mProgressPaint = new Paint();
        mProgressPaint.setStyle(Paint.Style.FILL_AND_STROKE);
        mProgressPaint.setStrokeWidth(2);
        mProgressPaint.setAntiAlias(true);

        mTextPaint = new Paint();
        mTextPaint.setStyle(Paint.Style.STROKE);
        mTextPaint.setTextSize(mTextSize);
        mTextPaint.setAntiAlias(true);

        mPicturePaint = new Paint();
        mPicturePaint.setStyle(Paint.Style.STROKE);
        mPicturePaint.setAntiAlias(true);
        setLayerType(LAYER_TYPE_SOFTWARE,null);

        inflate=inflate(context,R.layout.dialog_top_seekbar,null);
    }

    @Override
    protected void onSizeChanged(int w, int h, int oldw, int oldh) {
        super.onSizeChanged(w, h, oldw, oldh);
        mWidth = w;
        mHeight = h;

        mBackgroundPaint.setColor(mBackgroundColor);
        mProgressPaint.setColor(mProgressColor);
        mTextPaint.setColor(mTextColor);
    }

    @Override
    protected void onDraw(Canvas canvas) {
        super.onDraw(canvas);

        //绘制文本背景框
        drawPicture(canvas);
        //绘制文本
        drawText(canvas);
        //将原点坐标移到文本之下
        canvas.translate(0,mPicHeight);//因为图片底部有留白，导致图片与进度条的距离看起来偏大，所以减去一段距离
        //绘制背景圆角矩形
        drawBackgroud(canvas);
        //绘制进度矩形圆角
        drawProgress(canvas);
    }
    /**
     * 绘制文本背景框
     * @param canvas
     */
    private void drawPicture(Canvas canvas){
//        if(this.mProgress == 0)
//            return;
        float percent = this.mProgress / 100 * 1.0f;
        int width = (int) (percent * mWidth);
        Bitmap bitmap = getViewBitmap(R.layout.dialog_top_seekbar);
        mPicWidth = bitmap.getHeight();
        mPicHeight = bitmap.getWidth()+20;
        int pos = width - mPicWidth/2+4;
//        canvas.drawBitmap(bitmap,pos,0,mPicturePaint);
        if(this.mProgress< 6){
            canvas.drawBitmap(bitmap,pos+40,0,mPicturePaint);
        }else if(this.mProgress>95){
            canvas.drawBitmap(bitmap,pos-40,0,mPicturePaint);
        }else{
            canvas.drawBitmap(bitmap,pos,0,mPicturePaint);
        }
//        Drawable drawable = getResources().getDrawable(R.drawable.bg_info_window);
//        Bitmap bitmap = drawableToBitmap(drawable);


    }

    /**
     * view转bitmap
     * @param v
     * @return
     */
    /**

     * 把一个view转化成bitmap对象

     * */

    public  Bitmap getViewBitmap(int layoutId) {

        View view =  inflate(getContext(),layoutId, null);
        //设置布局背景透明
//        ImageView isb_progress=view.findViewById(R.id.isb_progress);
//        ImageView iv_bg=view.findViewById(R.id.iv_bg);
//        isb_progress.getBackground().setAlpha(80);
//        iv_bg.getBackground().setAlpha(80);


        int me = MeasureSpec.makeMeasureSpec(0,MeasureSpec.UNSPECIFIED);

        view.measure(me,me);

        view.layout(0 ,0, view.getMeasuredWidth(), view.getMeasuredHeight());

        view.buildDrawingCache();

        Bitmap bitmap = view.getDrawingCache();



        return bitmap;

    }
    /**
     * drawable转bitmap
     * @param drawable
     * @return
     */
    public static Bitmap drawableToBitmap(Drawable drawable) {
        // 取 drawable 的长宽
        int w = drawable.getIntrinsicWidth();
        int h = drawable.getIntrinsicHeight();

        // 取 drawable 的颜色格式
        Bitmap.Config config = drawable.getOpacity() != PixelFormat.OPAQUE ? Bitmap.Config.ARGB_8888
                : Bitmap.Config.RGB_565;
        // 建立对应 bitmap
        Bitmap bitmap = Bitmap.createBitmap(w, h, config);
        // 建立对应 bitmap 的画布
        Canvas canvas = new Canvas(bitmap);
        drawable.setBounds(0, 0, w, h);
        // 把 drawable 内容画到画布中
        drawable.draw(canvas);
        return bitmap;
    }
    /**
     * 绘制文本
     * @param canvas
     */
    private void drawText(Canvas canvas){
        if(this.mProgress == 0)
            return;
        float percent = this.mProgress / 100 * 1.0f;
        int width = (int) (percent * mWidth);
        float length = mTextPaint.measureText(mText);
        if(this.mProgress< 6){
            canvas.drawText(mText,width+length+10,mPicHeight/3,mTextPaint);
        }else if(this.mProgress>95){
            canvas.drawText(mText,width-length*2-8,mPicHeight/3,mTextPaint);
        }else{
            canvas.drawText(mText,width-length/2,mPicHeight/3,mTextPaint);
        }

    }
    /**
     * 绘制背景矩形圆角
     * @param canvas
     */
    private void drawBackgroud(Canvas canvas){
        RectF rectF = new RectF();
        rectF.left = 0;
        rectF.top = 0;
        rectF.right = mWidth;
        rectF.bottom = mProgressHeight;

        mRadiusArr[0] = 0;
        mRadiusArr[1] = 0;
        mRadiusArr[2] = 0;
        mRadiusArr[3] = 0;
        mRadiusArr[4] = 0;
        mRadiusArr[5] = 0;
        mRadiusArr[6] = 0;
        mRadiusArr[7] = 0;
        Path path = new Path();
        path.addRoundRect(rectF, mRadiusArr,Path.Direction.CW);
        canvas.drawPath(path,mBackgroundPaint);
    }

    /**
     * 绘制进度矩形圆角（只有左上和左下是圆角）
     * @param canvas
     */
    private void drawProgress(Canvas canvas){
        if(this.mProgress == 0)
            return;
        float percent = this.mProgress / 100 * 1.0f;
        int width = (int) (percent * mWidth);

        RectF rectF = new RectF();
        rectF.left = 0;
        rectF.top = 0;
        rectF.right = width;
        rectF.bottom = mProgressHeight;

        if (this.mProgress < 100){
            mRadiusArr[0] = 0;
            mRadiusArr[1] = 0;
            mRadiusArr[2] = 20;
            mRadiusArr[3] = 20;
            mRadiusArr[4] = 20;
            mRadiusArr[5] = 20;
            mRadiusArr[6] = 0;
            mRadiusArr[7] = 0;
        }else{
            allRoundRadius();
        }
        Path path = new Path();
        path.addRoundRect(rectF,mRadiusArr,Path.Direction.CW);
        canvas.drawPath(path,mProgressPaint);
    }
    /**
     * 4个角都是圆角
     */
    private void allRoundRadius(){
        mRadiusArr[0] = 20;
        mRadiusArr[1] = 20;
        mRadiusArr[2] = 20;
        mRadiusArr[3] = 20;
        mRadiusArr[4] = 20;
        mRadiusArr[5] = 20;
        mRadiusArr[6] = 20;
        mRadiusArr[7] = 20;
    }


    /**
     * xia
     */

    /**
     * 设置是否矩形4个角都是圆角
     * @param isAllRound
     */
    public void setFourRoundRect(boolean isAllRound){
        if (isAllRound){
            allRoundRadius();
        }
        invalidate();
    }

    /**
     * 设置进度值0-100
     * @param progress
     */
    public void setProgress(float progress){
        this.mProgress = progress;
        invalidate();
    }

    /**
     * 设置文本
     * @param text
     */
    public void setText(String text){
        this.mText = text;
        invalidate();
    }

    public void  setBackgroundColor(int backgroundColor){
        this.mBackgroundColor = backgroundColor;
        invalidate();
    }

    public void  setProgressColor(int progressColor){
        this.mProgressColor = progressColor;
        invalidate();
    }

    public void  setTextColor(int textColor){
        this.mTextColor = textColor;
        invalidate();
    }

}
